var db = require('../config/db.js').redis
var  passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy;
var session = require('express-session')
var RedisStore = require('connect-redis')(session);
var config = require('../config/config')
var neo = require('../config/neo4j.js')
var denodeify = require('../helper/denodeify')
exports.session = session({
  store: new RedisStore({
    host: config.redis.host,
    port: config.redis.port,
    db: 1,
    pass: config.redis.password
  }),
  cookie: { maxAge: 600000},//redis key auto expires in the same time
  secret: config.session_secret,
  resave: false,
  saveUninitialized: false
})

passport.use('local', new LocalStrategy(
    async function(username, password, done){
        try{
        let query_res = await denodeify(neo.getUser)(username);
        if(query_res.length == 0)
            return done(null, false, { message: 'Incorrect username.'})
        if(password !== query_res[0]['u']['properties']['password'])
            return done(null, false, { message: 'Incorrect password'})
        return done(null, query_res[0]['u'])
        }catch(err){
            console.log(err)
            done(err)
        }
    }
));

passport.serializeUser(function (user, done) {
    //在LocalStrategy通过后调用，传入生成的user，得到要序列化存储在Redis值中的信息
    done(null, user);
});

passport.deserializeUser(function (session_content, done) {
    //根据cookie中的connect.sid自动去数据库判断登录，通过得到的值生成req.user
    (async function(){
        done(null, session_content);
    })();
    
});

function isLoggedIn(req, res, next) {
    console.log(req.cookies)
    console.dir(req.session)
    if (req.isAuthenticated())
        return next();
    res.redirect('/');
}
exports.isLoggedIn = isLoggedIn;
exports.passport = passport;